<template>
    <div>
        <app-search>
            <el-form :model="order" :label-position="$store.labelPosition"
                     label-width="30%" ref="order" :rules="rules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务员：" prop="sellMan">
                            <el-select v-model="order.sellMan" clearable placeholder="请选择业务员"
                                       :disabled="isView">
                                <el-option v-for="sell in sells" :key="sell.userId"
                                           :label="sell.username" :value="sell.userId"></el-option>
                            </el-select>
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单号：" prop="orderNo">
                            <el-input v-model="order.orderNo" :disabled="isView || isEditOrder"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户：" prop="custId">
                            <el-select v-model="order.custId" filterable  clearable
                                       placeholder="请选择客户"
                                       @change="changeCustomer()" :disabled="isView">
                                <el-option v-for="cust in customers" :key="cust.id"
                                           :label="cust.name" :value="cust.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人：" prop="contactId">
                            <el-select v-model="order.contactId" clearable placeholder="请选择联系人"
                                       :disabled="isView">
                                <el-option v-for="contact in contacts" :key="contact.id"
                                           :label="contact.name" :value="contact.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="接单日期：" prop="orderDt">
                            <el-date-picker type="date" placeholder="接单日期" v-model="order.orderDt"
                                            :disabled="isView" value-format="yyyy-MM-dd"
                                            format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="付款日期：" prop="payDt">
                            <el-date-picker type="date" placeholder="付款日期" v-model="order.payDt"
                                            :disabled="isView" value-format="yyyy-MM-dd"
                                            format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>

                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="总价：" prop="totalAmount">
                            <el-input-number v-model="order.totalAmount" :disabled="isView"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开票公司：" prop="receiptCompany">
                            <el-select v-model="order.receiptCompany" clearable
                                       placeholder="请选择" style="width: 100%;" :disabled="isView">
                                <el-option v-for="st in receiptCompanies" :key="st.code"
                                           :label="st.description" :value="st.code">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="要求出货日期：" prop="requireOutDt">
                            <el-date-picker type="date" placeholder="接单日期" v-model="order.requireOutDt"
                                            :disabled="isView" value-format="yyyy-MM-dd"
                                            format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单状态：" >
                            <el-tag type="danger" v-if="order.status == 0">{{order.statusDescr}}</el-tag>
                            <el-tag type="warning" v-if="order.status == 1">{{order.statusDescr}}</el-tag>
                            <el-tag type="success" v-if="order.status == 2">{{order.statusDescr}}</el-tag>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：" label-width="15%">
                            <el-input type="textarea" :row="3" v-model="order.remark"
                                      :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row >
                    <el-col :span="24">
                        <el-form-item label-width="15%">
                            <el-button type="edit" icon="fa fa-save" @click="submitForm()" v-if="!isView">
                                保存
                            </el-button>

                            <el-button type="edit" icon="el-icon-plus" v-if="isEditOrder && !isView"
                                       @click="showAddOrderItem()">添加产品</el-button>
                            <el-button type="danger" icon="el-icon-delete" v-if="isEditOrder && !isView"
                                       @click="deleteOrderItems()" >删除产品</el-button>

                            <el-button type="primary" icon="el-icon-back" @click="cancel()">
                                返回
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </app-search>

        <template v-if="isEditOrder">
        <order-item-list v-bind:tableData="orderItems"></order-item-list>

        <order-item-edit v-bind:orderItem="orderItem"></order-item-edit>
        </template>

    </div>

</template>

<script>
import OrderItemEdit from './order_item_edit';
import OrderItemList from './order_item_list';
import { mapState } from 'vuex';
import {validateNumber} from '@/util/rules'

export default {
    name: "OrderEdit",
    components: {OrderItemList, OrderItemEdit},
    data() {
        return {
            order: {},
            contacts: [],
            tableData: {
                loading: true,
                body: []
            },
            rules:{
                sellMan:[{ required: true, message: '请选择业务员', trigger: ['blur'] }],
                custId:[{ required: true, message: '请选择客户', trigger: ['blur'] }],
                contactId:[{ required: true, message: '请选择联系人', trigger: ['blur'] }],
                orderDt:[{ required: true, message: '请选择订单日期', trigger: 'blur' }],
                totalAmount:[{ validator: validateNumber, trigger: 'blur' }],
                payDt:[{ required: true, message: '请选择付款日期', trigger: ['blur'] }],
                receiptCompany:[{ required: true, message: '请选择发票抬头', trigger: ['blur'] }],
            }
        }
    },
    mounted() {
        console.log("isView: ", this.$store.isView)
        this.initOrder()
    },

    methods: {
        // 获取订单数据
        async initOrder() {
            console.log("orderId=", this.orderId);
            let res = await this.$axios.get(`/sell/order/${this.orderId}`);
            console.log("返回订单信息：", res);
            this.order = res.result.order;
            this.contacts = res.result.contactList;
            this.tableData.loading = false;
            this.$store.commit("order/Set_Order_Items", res.result.orderItems);
        },

        showAddOrderItem(){
            this.$store.commit("order/Show_Add_Order_Item")
        },

        submitForm(){
            this.$refs['order'].validate((valid) => {
                if(valid){
                    this.saveOrder();
                }
            });
        },

        async saveOrder(){
            if(this.isEditOrder){
                await this.$axios.put('/sell/order', this.order);
                this.$myMsg.success('成功修改订单信息。');
            }else{
                let res = await this.$axios.post('/sell/order', this.order);
                this.$myMsg.success('成功创建订单信息。请增加订单项信息。');
                console.log("创建订单后返回：", res);
                this.$store.dispatch('order/showEditOrder', res.result);
                this.initOrder();
            }
        },

        async changeCustomer(){
            let res = await this.$axios.get(`/company/contact/findByCompanyId/${this.order.custId}`);
            console.log("返回的联系人列表：", res);
            this.contacts = res.result;
            this.order.contactId = "";
        },

        deleteOrderItems(){
            if(this.selectedItems.length === 0){
                this.$myMsg.warning("请选择要删除的订单项")
                return;
            }

            this.$confirm('确实要删除选中的订单项吗？', '确认信息', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            })
            .then(() => {
                this.actualDeleteOrderItems();
            })
            .catch(action => {
                this.$myMsg.info('已放弃删除选中的订单项。');
            });
        },

        async actualDeleteOrderItems(){
            let deletedIds = "";
            this.selectedItems.forEach( item => {
                deletedIds += item.id + ",";
            });

            await this.$axios.delete(`/sell/orderItem/batchRemove/${deletedIds}`);
            this.$myMsg.success('删除成功');
            this.$store.dispatch("order/removeOrderItems");
        },

        cancel(){
            this.$store.commit("order/Set_Show_Edit_Order", false);
        }

    },

    computed: {
        ...mapState({
            customers: state => state.order.initPageData.customers,
            sells: state => state.order.initPageData.sells,
            orderItems: state => state.order.orderItems,
            orderId: state => state.order.orderId,
            orderItem: state => state.order.orderItem,
            selectedItems: state => state.order.selectedItems,
            isView: state => state.order.isView,
            receiptCompanies: state => state.order.initPageData.receiptCompanies,
            statusList: state => state.order.initPageData.statusList,
        }),

        isEditOrder(){
            return this.orderId > -1
        },

        totalPrice(){
            let total = 0.00;
            if(this.orderItems){
                console.log("当前产品：", this.orderItems);
                for(let i = 0; i < this.orderItems.length; i++){
                    total = total + this.orderItems[i].price * this.orderItems[i].num;
                }
            }

            return total;
        }
    }
}
</script>

